package com.huabo.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>ClassName: FileUtils</p>
 * <p>Description: 文件操作工具类</p>
 * <p>Author: Jackie Liu</p>
 * <p>Date: 2015年3月20日</p>
 */
public class FileUtils {
	
	/**
	 * <p>Description: 创建文件夹</p>
	 * @param pathName 文件夹路径
	 * @return
	 */
	public static boolean mkdir(String pathName) {
		File path = new File(pathName);
		if (!path.exists()) {
			return path.mkdirs();
		}
		return true;
	}
	
	/**
	 * <p>Description: 删除文件(非文件夹)</p>
	 * @param pathName 文件路径
	 */
	public static void remove(String pathName) {
		File file = new File(pathName);
		if(file.exists()) {
			if(file.isFile()) {
                file.delete();
            }
		}
	}
	
	/**
	 * <p>Description: 文本文件追加内容</p>
	 * @param pathName
	 * @param content
	 * @return
	 */
	public static boolean writeAfter(String pathName, String content){
		try {
			FileWriter fw = new FileWriter(pathName, true);
			fw.write(content);
			fw.close();
			return true;
		} catch(Exception e) {
			e.printStackTrace();
			return false;
		}		
	}	
	
	/**
	 * <p>Description: 写入文本文件</p>
	 * @param file
	 * @param content
	 * @return
	 */
	public static boolean write(File file, String content) {
		boolean b = true;
		try {
			if(!file.exists()) {
				mkdir(file.getParentFile().getPath());
				file.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(content.getBytes());
			fos.flush();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
			b = false;
		}
		return b;
	}	
	
	/**
	 * <p>Description: 获取文件的mime类型</p>
	 * @param fileName 文件名称
	 * @return
	 */
	public static String getContentType(String fileName) {
        String fileNameTmp = fileName.toLowerCase();
        String ret = "";
        if (fileNameTmp.endsWith("txt")) {
            ret = "text/plain";
        } else if (fileNameTmp.endsWith("gif")) {
            ret = "image/gif";
        } else if (fileNameTmp.endsWith("jpg")) {
            ret = "image/jpeg";
        } else if (fileNameTmp.endsWith("jpeg")) {
            ret = "image/jpeg";
        } else if (fileNameTmp.endsWith("jpe")) {
            ret = "image/jpeg";
        } else if (fileNameTmp.endsWith("zip")) {
            ret = "application/zip";
        } else if (fileNameTmp.endsWith("rar")) {
            ret = "application/rar";
        } else if (fileNameTmp.endsWith("doc")) {
            ret = "application/msword";
        } else if (fileNameTmp.endsWith("ppt")) {
            ret = "application/vnd.ms-powerpoint";
        } else if (fileNameTmp.endsWith("xls")) {
            ret = "application/vnd.ms-excel";
        } else if (fileNameTmp.endsWith("html")) {
            ret = "text/html";
        } else if (fileNameTmp.endsWith("htm")) {
            ret = "text/html";
        } else if (fileNameTmp.endsWith("tif")) {
            ret = "image/tiff";
        } else if (fileNameTmp.endsWith("tiff")) {
            ret = "image/tiff";
        } else if (fileNameTmp.endsWith("pdf")) {
            ret = "application/pdf";
        } else if (fileNameTmp.endsWith("chm")){
        	ret = "application/octet-stream";
        } else if (fileNameTmp.endsWith("apk")) {
        	ret = "application/vnd.android.package-archive";
        } else if (fileNameTmp.endsWith("properties")) {
        	ret = "text/properties";
        }
        return ret;
    }
	
	/**
	 * <p>Description: 删除文件夹</p>
	 * @param folderPath
	 */
	public static void delFolder(String folderPath) {
	    try {
	    	delAllFile(folderPath);
	    	File myFilePath = new File(folderPath);
	    	myFilePath.delete();
	    }catch (Exception e) {
			e.printStackTrace();
		}
	}	
	
	/**
	 * <p>Description: 删除该路径下的所有文件</p>
	 * @param path
	 */
	public static void delAllFile(String path) {
	    File file = new File(path);
	    if (!file.exists()) {
	    	return;
	    }
	    if (!file.isDirectory()) {
	    	return;
	    }
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
		    	temp = new File(path + tempList[i]);
		    }else{
		        temp = new File(path + File.separator + tempList[i]);
		    }
		    if (temp.isFile()) {
		    	temp.delete();
		    }
		    if (temp.isDirectory()) {
		    	delAllFile(path+"/"+ tempList[i]);
		    	delFolder(path+"/"+ tempList[i]);
		    }
		}
	}
	
	
    /**
     * 删除单个文件
     * @param  sPath  被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
	
	
    /**
     * <p>Description: 获得指定路径下的所有file </p>
     * @param fileDir：路径
     * @return list
     */
    public static List<File> getFiles(String fileDir){
        File dir = new File(fileDir);
        List<File> list = new ArrayList<File>();
        findFile(dir, list);
        return list;
    }
    
    private static void findFile(File dir, List<File> list) {
        File[] files = dir.listFiles();
        if ((files != null) && (files.length > 0)) {
            for (int i = 0; i < files.length; ++i) {
                File file = files[i]; 
                if (file.isDirectory()) {
                    findFile(file, list);
                } else {
                    list.add(file);
                }     
     
            }     
        }     
    }
    
    /**
     * <p>Description: 获得指定路径下的所有file名称</p>
     * @param fileDir：路径
     * @return list
     */
    public static List<String> getFilesNameList(String fileDir){
        File dir = new File(fileDir);
        List<File> fileList = new ArrayList<File>();
        findFile(dir, fileList);
        List<String> list = new ArrayList<String>();
        if (fileList != null) {
        	for (File file : fileList) {
        		list.add(file.getName());
        	}
        }
        return list;
    }
    
    /**
     * <p>Description: 写入TXT文件</p>
     * @param content 内容
     * @param path 文件路径
     */
    public static void writeTxt(String content, String path) throws RuntimeException {
    	BufferedWriter bw = null;
    	try {
    		String strEncode = "UTF-8";
    		
    		File file = new File(path);
        	if (!file.exists()) {
        		file.createNewFile();
        	}
        	bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), strEncode));
            bw.write(content);
            bw.flush();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		} finally {
			try {
				if (bw != null) {
					bw.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
    }
    
    /**
     * <p>Description: 读取TXT文件</p>
     * @param path 文件路径
     * @return
     */
    public static String readTxt(String path) throws RuntimeException {
    	BufferedReader bufferedReader = null;
    	StringBuffer sb = new StringBuffer();
    	try {
    		File file = new File(path);
    		if (!file.exists()) {
    			return null;
    		}
			bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			String read = null;  
		    while((read = bufferedReader.readLine())!=null){  
		    	sb.append(read);
		    }  
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new RuntimeException();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException();
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
    }
}
